package com.asia5b.a5mall.member.widget

import android.content.Context
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.adapter.UploadAdapter
import com.asia5b.a5mall.middleware.utils.StringUtils
import com.luck.picture.lib.entity.LocalMedia
import kotlinx.android.synthetic.main.view_upload.view.*

class UploadView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    var uploadPosition: Int = 0
        set(value) {
            field = value
            mAdapter.uploadPosition = value
        }
    var mRecyclerView: RecyclerView
    val mDatas = arrayListOf<LocalMedia>()
    var selectionMedia: ArrayList<LocalMedia>? = null
        set(value) {
            field = value
            mAdapter.selectionMedia=field
            notifyDatas()
        }
    val mAdapter = UploadAdapter(mDatas)

    init {
        View.inflate(context, R.layout.view_upload, this)
        mRecyclerView = findViewById(R.id.rv_upload)
        mRecyclerView.run {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = mAdapter
        }
        notifyDatas()
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            selectionMedia?.run {
                if (this.size > position) {
                    this.removeAt(position)
                    notifyDatas()
                }
            }

        }
        var text=ResString.get(R.string.上传照片_数)
        val spanText = StringUtils.setTextColor(text, "5", ContextCompat.getColor(context,R.color.colorPrimaryDark))
        tv_upload_max.setText(spanText)
    }

    fun notifyDatas() {
        mDatas.clear()
        selectionMedia?.run {
            mDatas.addAll(this)
        }
        addDefault()
        mAdapter.notifyDataSetChanged()
    }

    fun addDefault() {
        if (mDatas.size < 5) {
            var hasAddButton = false
            for ((index, localMedia) in mDatas.withIndex()) {
                if (localMedia.position == -1) {
                    hasAddButton = true
                    break
                }
            }
            if (!hasAddButton) {
                val localMedia = LocalMedia()
                localMedia.position = -1
                mDatas.add(localMedia)
            }
        } else {
            for ((index, localMedia) in mDatas.withIndex()) {
                if (localMedia.position == -1) {
                    mDatas.removeAt(index)
                    break
                }
            }
        }
    }

}